<script setup>
import { ref, reactive } from "vue";
import baseModel from "@/components/baseModel/baseModel.vue";
import request from "@/common/utils/request";
import { message, Empty } from "ant-design-vue";
import {
    PlayCircleOutlined,
} from "@ant-design/icons-vue";

import { useRouter } from "vue-router";

// 预览视频弹窗
import viewVideo from '@/views/shotstack/components/dialogComponent/viewVideo.vue'
const viewVideoRef = ref()

import { useStore } from "vuex";
const store = useStore();


const router = useRouter();
const emit = defineEmits(["selectHuman:item"]);

const scrollBox = ref();
const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE

const activeKey = ref('1')

// 是否有公共形象权限
const has_public_digital_human = ref(false)

// 数字人列表
const humanRecordList = ref([])

// 公共形象列表
const humanPublicList = ref([])

const serchData =reactive({
    page: 1,
    pageSize: 12,
    total: 0, 
    last_page: 0,
})

const notmore = ref(false)

// 数字人列表
const getHumanRecord = () => {
  const params = {
    page: serchData.page,
    pageSize: serchData.pageSize,
  };
  // /digital/human/record
  request
    .get("/work_ai", "/digital/human/record", params)
    .then((res) => {
      console.log(res, "列表数据");
      humanRecordList.value.push(...res.result.data);
      serchData.total = res.result.total;
      serchData.last_page = res.result.last_page;
      if (serchData.page >= res.result.last_page) {
        notmore.value = true;
      }
    })
    .catch((err) => {});
};

// 数字人公共列表
const getPublicList = async () => {

  // 获取 workAi 系统配置 -- 用于判断选择素材 是否包含网络素材
  const list = await store.dispatch("getAiConfig")
  console.log(list, '有没有权限呢??');
  
  has_public_digital_human.value = !!list?.has_public_digital_human

  if (has_public_digital_human.value == true) {  
    const res = await request
      .get("/work_ai", "/digital/human/public/list")
    console.log(res, '公共形象列表');
    humanPublicList.value = res?.result || []
 }
} 

const handleScroll = () => {
  if (
    scrollBox.value.scrollTop + scrollBox.value.clientHeight >=
    scrollBox.value.scrollHeight
  ) {
    // 触底时请求下一页数据
    const { last_page, page } = serchData;
    if (page >= last_page) {
      notmore.value = true;
      return;
    }
    serchData.page++;
    getHumanRecord();
  }
};

// 创建数字人
const goAIdigitalHuman = () => {
  router.push({
    name: "AIdigitalHuman",
    query: { type: "AIdigitalHumanCreatVideo" },
  });
};

// 只能单选的逻辑
const checkboxChange = ({ target }, item) => {
  const checked = target.checked;
  if (checked) {
    if (activeKey.value == 1) {        
      humanRecordList.value.forEach((ele) => {
          if(ele.id !== item.id){
              ele.checked = false
          }
      }) 
      humanPublicList.value.forEach((ele) => {
            ele.checked = false
      }) 
    } else {
      humanPublicList.value.forEach((ele) => {
          if(ele.id !== item.id){
              ele.checked = false
          }
      }) 
      humanRecordList.value.forEach((ele) => {
            ele.checked = false
      }) 
       }
    }
}


// 选择数字人
const submit = () => {
  let selectHuman
  if (activeKey.value == 1) {
    selectHuman = humanRecordList.value.find((ele) => ele?.checked)
  } else {
    selectHuman = humanPublicList.value.find((ele) => ele?.checked)
  }
  
    if(!selectHuman){
        close()
        return
    }
    emit('selectHuman', selectHuman)
    close()
}

const resetData = () => {
    Object.assign(serchData, {
        page: 1,
        pageSize: 10,
        total: 0, 
        last_page: 0,
    })
    humanRecordList.value = []
    notmore.value = false
}

// 预览视频
const toviewVideo = (url) => {
  if (url) {
    viewVideoRef.value?.open(url)
  }
};

const selectItem = (item) => {
  item.checked = !item.checked
  checkboxChange({target: {checked: item.checked}}, item)
}

const dialog = ref(null);
const open = () => {
    dialog.value.showModal();
  getHumanRecord()
  // 公共形象列表
  getPublicList()
};
const close = () => {
    dialog.value.closeModal();
};

defineExpose({
    open,
    close,
});
</script>

<template>
    <baseModel @isClose="resetData" :title="'选择形象'" ref="dialog" :contentWidth="800">
        <template #content>
          <a-tabs v-model:activeKey="activeKey">
          <a-tab-pane key="1" tab="自建">
            <div class="content" @scroll="handleScroll" ref="scrollBox" v-if="humanRecordList.length">
                    <div class="list_item" v-for="item in humanRecordList" :key="item.id"  @click="selectItem(item)">
                      <a-checkbox class="check_box" :disabled="item.disabled" v-model:checked="item.checked" @change="checkboxChange($event, item)"/>
                      <template v-if="!item.url_image">
                        <video :src="item.video_url" style="height: 130px"></video>
                      </template>
                      <template v-else>
                        <img :src="item.url_image" style="height: 130px; width: auto" />
                      </template>
                      <PlayCircleOutlined class="icon_PlayCircleOutlined" @click.stop="toviewVideo(item.video_url)">
                      </PlayCircleOutlined>
                      <div class="mask-box mask_name">
                        <span class="is_span">
                          {{ item.name }}
                        </span>
                      </div>
                    </div>
                    <p class="not_more" v-if="notmore">没有更多啦~</p>
                </div>

                <div v-else class="not_data_box" >
                    <div>
                    <a-empty :image="simpleImage" style="margin: 0 auto" />
                  </div>
                  <div class="not_data">
                    <span>您还没有数字人形象</span>
                    <a-button type="link" @click="goAIdigitalHuman">去创建</a-button>
                  </div>
                </div>

          </a-tab-pane>
          <a-tab-pane key="2" tab="公共" force-render v-if="has_public_digital_human">
            <div class="content" v-if="humanPublicList.length">
                    <div class="list_item" v-for="item in humanPublicList" :key="item.id" @click="selectItem(item)">
                      <a-checkbox class="check_box" :disabled="item.disabled" v-model:checked="item.checked" @change="checkboxChange($event, item)"/>
                      <template v-if="!item.url_image">
                        <video :src="item.video_url" style="height: 130px"></video>
                      </template>
                      <template v-else>
                        <img :src="item.url_image" style="height: 130px; width: auto" />
                      </template>
                      <PlayCircleOutlined class="icon_PlayCircleOutlined" @click.stop="toviewVideo(item.video_url)">
                      </PlayCircleOutlined>
                      <div class="mask-box mask_name">
                        <span class="is_span">
                          {{ item.name }}
                        </span>
                      </div>
                    </div>
                    <p class="not_more" v-if="notmore">没有更多啦~</p>
                </div>

                <div v-else class="not_data_box" >
                    <div>
                    <a-empty :image="simpleImage" style="margin: 0 auto" />
                  </div>
                  <div class="not_data">
                    <span>暂无公共形象</span>
                  </div>
                </div>
          </a-tab-pane>
        </a-tabs>

        </template>
        <template #footer>
          <a-button @click="close">取消</a-button>
            <a-button @click="submit" type="primary">确定</a-button>
        </template>
    </baseModel>

    <viewVideo ref="viewVideoRef"></viewVideo>
</template>



<style lang="less" scoped>
 @radius: 8px;
 @pd: 15px;

 .not_data_box{
    height: 300px; 
    display: flex;
    flex-direction: column;
    justify-content: center;

     .not_data{
         display: flex;
         justify-content: center;
         align-items: center;
     }

 }

.content {
        // height: 500px;
        width: 100%;
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-gap: 15px;
        align-content: start;
        // gap: 15px;
        overflow-y: auto;
        // padding-bottom: 40px;
        padding-top: 10px;

        .not_more{
          grid-column: 1 / -1;
          text-align: center;
        }

        &::-webkit-scrollbar {
          width: 5px;
          /* 滚动条的宽度 */
          height: 10px;
          /* 滚动条的高度，垂直滚动条可能用得上 */
        }

        &::-webkit-scrollbar-thumb {
          background: #c4c4c4;
          /* 滑块的背景颜色 */
          border-radius: 10px;
          /* 滑块的圆角 */
        }

        .list_item {
          height: 130px;
        //   width: 247px;
        width: 100%;
          border-radius: @radius;
          overflow: hidden;
          position: relative;
          cursor: pointer;
          text-align: center;
          background: #000;

          // 遮罩
          &::after {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            height: 100%;
            width: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            transition: all 0.3s;
            opacity: 0;
          }

          &:hover {
            &::after {
              opacity: 1;
            }

            .icon_PlayCircleOutlined {
              opacity: 1;
            }
          }

          img {
            // width: auto;
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .check_box {
            position: absolute;
            top: 5px;
            right: 5px;
            z-index: 3;
          }

          .icon_PlayCircleOutlined {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            font-size: 36px;
            color: #fff;
            transition: all 0.3s;
            opacity: 0;
            z-index: 2;

            &:hover {
              color: var(--ss-primary-color-hover);
            }
          }

          .mask_name {
            padding: 0 10px;

            .is_span {
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 1;
              -webkit-box-orient: vertical;
              width: auto;
            }

            // 一行显示
          }

          .mask-box {
            position: absolute;
            width: 100%;
            height: 30px;
            background: rgba(0, 0, 0, 0.5);
            bottom: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #fff;
            font-size: 13px;
          }
        }

        .empty-box {
          width: 100%;
          flex-direction: column;
          text-align: center;
          justify-content: center;
        }
      }
</style>